package com.xyh.web.admin;

import com.xyh.pojo.PageRequest;
import com.xyh.pojo.PageResult;
import com.xyh.pojo.Type;
import com.xyh.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class TypeController {
    @Autowired
    private TypeService service;

    @GetMapping("/types")
    public String types(PageRequest pageQuery,Model model) {
        PageResult page = service.getPage(pageQuery);
        model.addAttribute("page",page);
        return "admin/types";
    }
    @GetMapping("/types/input")
    public String input(Model model) {
        model.addAttribute("type", new Type());
        return "admin/type-input";
    }
    @GetMapping("/types/{id}/input")
    public String editInput(@PathVariable("id") Long id,Model model) {
        model.addAttribute("type", service.getType(id));
        return "admin/type-input";
    }
    @PostMapping("/types")
    public String post(@Validated Type type, BindingResult result, RedirectAttributes attributes) {
        Type t = service.getTypeByName(type.getName());
        if (t!=null) {
            result.rejectValue("name","nameError","不能添加重复分类");
        }
        if (result.hasErrors()) {
            return "admin/type-input";
        }
        int i = service.saveType(type);
        if (i>=1) {
            attributes.addFlashAttribute("message", "添加成功！");
        }else {
            attributes.addFlashAttribute("message", "添加失败！");
        }
        return "redirect:/admin/types";
    }
    @PostMapping("/types/{id}")
    public String editPost(@Validated Type type, BindingResult result, @PathVariable Long id, RedirectAttributes attributes) {
        Type t = service.getTypeByName(type.getName());
        if (t!=null) {
            result.rejectValue("name","nameError","不能添加重复分类");
        }
        if (result.hasErrors()) {
            return "admin/type-input";
        }
        int i = service.updateType(id,type);
        if (i>=1) {
            attributes.addFlashAttribute("message", "编辑成功！");
        }else {
            attributes.addFlashAttribute("message", "编辑失败！");
        }
        return "redirect:/admin/types";
    }
    @GetMapping("/types/delete/{id}")
    public String delete(@PathVariable Long id,RedirectAttributes attributes){
        service.deleteType(id);
        attributes.addFlashAttribute("message", "删除成功！");
        return "redirect:/admin/types";
    }
}
